package com.car.carmgr.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExlExportUtil {

    /**
     * 2.生成excel文档，保存到磁盘
     */
    public static void createExcelToFile(){

        // 创建Excel文档对象
        HSSFWorkbook workbook = createExcel();

        try {
            /**
             * 导出所以用到输出流
             * 参数为输出的地址
             */
            FileOutputStream fout = new FileOutputStream("E:\\poi.xls");

            workbook.write(fout);   //Workbook提供了write的方法
            fout.close();           //将输出流关闭
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static HSSFWorkbook createExcel(){

        // 创建Excel文档对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFCellStyle style = workbook.createCellStyle();

        // 创建sheet对象
        HSSFSheet sheet1 = workbook.createSheet();
        // 设置单元格默认宽高
        sheet1.setDefaultRowHeight((short)(20*20));
        sheet1.setDefaultColumnWidth(10);

        // 创建第一行
        HSSFRow row1 = sheet1.createRow(0);
        // 创建第一列
        HSSFCell row1_cell1 = row1.createCell(0);
        row1_cell1.setCellValue("编号");
        HSSFFont hssfFont = workbook.createFont();
        hssfFont.setFontName("幼圆");
        hssfFont.setColor(Font.COLOR_RED);
        hssfFont.setFontHeight((short)(30*30));
        style.setFont(hssfFont);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // 修改单元格样式
        row1_cell1.setCellStyle(style);

        // 创建第二列
//        HSSFCell row1_cell2 = row1.createCell(1);
//        row1_cell2.setCellValue("姓名");

        // 合并单元格
        CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 6);
        sheet1.addMergedRegion(cellRangeAddress);

        return  workbook;

    }


    public static ByteArrayOutputStream createExcelToStream() {
        HSSFWorkbook excel = createExcel();
        // 输出到ByteArrayOutputStream 对象中
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            excel.write(baos);
//            baos.flush();
//            baos.close();
            return baos;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        createExcelToFile();
    }
}
